<template>
  <div class="data-flow-manager">
    <div class="flow-header">
      <h3>数据处理流程</h3>
      <el-button size="small" @click="showFlowDialog = true">
        <el-icon><Plus /></el-icon>
        新建流程
      </el-button>
    </div>
    
    <div class="flow-steps">
      <div class="step-item" :class="{ 'active': currentStep === 1, 'completed': currentStep > 1 }">
        <div class="step-number">1</div>
        <div class="step-content">
          <h4>数据导入</h4>
          <p>导入Excel、CSV等数据文件</p>
          <el-button v-if="currentStep === 1" size="small" type="primary" @click="goToImport">
            开始导入
          </el-button>
        </div>
      </div>
      
      <el-icon class="step-arrow"><ArrowRight /></el-icon>
      
      <div class="step-item" :class="{ 'active': currentStep === 2, 'completed': currentStep > 2 }">
        <div class="step-number">2</div>
        <div class="step-content">
          <h4>数据清洗</h4>
          <p>清理空值、重复数据和异常值</p>
          <el-button v-if="currentStep === 2" size="small" type="primary" @click="goToCleaning">
            开始清洗
          </el-button>
        </div>
      </div>
      
      <el-icon class="step-arrow"><ArrowRight /></el-icon>
      
      <div class="step-item" :class="{ 'active': currentStep === 3, 'completed': currentStep > 3 }">
        <div class="step-number">3</div>
        <div class="step-content">
          <h4>数据建模</h4>
          <p>建立表关系和计算字段</p>
          <el-button v-if="currentStep === 3" size="small" type="primary" @click="goToModeling">
            开始建模
          </el-button>
        </div>
      </div>
      
      <el-icon class="step-arrow"><ArrowRight /></el-icon>
      
      <div class="step-item" :class="{ 'active': currentStep === 4, 'completed': currentStep > 4 }">
        <div class="step-number">4</div>
        <div class="step-content">
          <h4>报表设计</h4>
          <p>创建可视化图表和报表</p>
          <el-button v-if="currentStep === 4" size="small" type="primary" @click="goToDesigner">
            开始设计
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 数据流程状态 -->
    <div class="flow-status">
      <div class="status-header">
        <h4>当前数据状态</h4>
      </div>
      
      <div class="status-content">
        <div class="status-item">
          <span class="status-label">数据源:</span>
          <span class="status-value">{{ dataSourceCount }} 个</span>
        </div>
        <div class="status-item">
          <span class="status-label">已清洗:</span>
          <span class="status-value">{{ cleanedDataCount }} 个</span>
        </div>
        <div class="status-item">
          <span class="status-label">数据模型:</span>
          <span class="status-value">{{ modelCount }} 个</span>
        </div>
        <div class="status-item">
          <span class="status-label">报表:</span>
          <span class="status-value">{{ reportCount }} 个</span>
        </div>
      </div>
    </div>
    
    <!-- 快速操作 -->
    <div class="quick-actions">
      <div class="actions-header">
        <h4>快速操作</h4>
      </div>
      
      <div class="actions-content">
        <el-button @click="importSampleData">
          <el-icon><Download /></el-icon>
          导入示例数据
        </el-button>
        <el-button @click="createQuickReport">
          <el-icon><Grid /></el-icon>
          快速报表
        </el-button>
        <el-button @click="exportData">
          <el-icon><Upload /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>
    
    <!-- 流程创建对话框 -->
    <el-dialog v-model="showFlowDialog" title="创建数据流程" width="600px">
      <el-form :model="flowForm" label-width="100px">
        <el-form-item label="流程名称">
          <el-input v-model="flowForm.name" placeholder="输入流程名称" />
        </el-form-item>
        <el-form-item label="数据源">
          <el-upload
            class="upload-demo"
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1">
            <el-icon class="el-icon--upload"><Upload /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 .xlsx, .xls, .csv 格式文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="自动处理">
          <el-checkbox-group v-model="flowForm.autoSteps">
            <el-checkbox value="clean">自动清洗</el-checkbox>
            <el-checkbox value="model">自动建模</el-checkbox>
            <el-checkbox value="report">生成报表</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showFlowDialog = false">取消</el-button>
        <el-button type="primary" @click="createFlow">创建流程</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useDataCleaningStore } from '../stores/dataCleaningStore'
import { useDataModelStore } from '../stores/dataModelStore'
import { useTableStore } from '../stores/tableStore'
import { ElMessage } from 'element-plus'
import { 
  Plus, 
  ArrowRight, 
  Download, 
  Upload, 
  Grid 
} from '@element-plus/icons-vue'

// 路由和stores
const router = useRouter()
const dataCleaningStore = useDataCleaningStore()
const dataModelStore = useDataModelStore()
const tableStore = useTableStore()

// 响应式数据
const currentStep = ref(1)
const showFlowDialog = ref(false)
const flowForm = ref({
  name: '',
  file: null,
  autoSteps: []
})

// 计算属性
const dataSourceCount = computed(() => dataCleaningStore.dataSources?.length || 0)
const cleanedDataCount = computed(() => dataCleaningStore.cleanedDataSources?.length || 0)
const modelCount = computed(() => dataModelStore.dataSources?.length || 0)
const reportCount = computed(() => tableStore.reportConfig?.visualizations?.length || 0)

// 方法
const goToImport = () => {
  router.push('/data-cleaning')
}

const goToCleaning = () => {
  router.push('/data-cleaning')
}

const goToModeling = () => {
  router.push('/data-model')
}

const goToDesigner = () => {
  router.push('/designer')
}

const handleFileChange = (file) => {
  flowForm.value.file = file.raw
}

const createFlow = async () => {
  if (!flowForm.value.name || !flowForm.value.file) {
    ElMessage.warning('请填写流程名称并选择文件')
    return
  }
  
  try {
    // 模拟文件处理
    const fileData = await processFile(flowForm.value.file)
    
    // 1. 添加到数据清洗
    const dataSource = dataCleaningStore.addDataSource({
      name: flowForm.value.name,
      type: getFileType(flowForm.value.file.name),
      data: fileData.data,
      columns: fileData.columns,
      rowCount: fileData.data.length
    })
    
    // 2. 自动清洗
    if (flowForm.value.autoSteps.includes('clean')) {
      dataCleaningStore.applyCleaningRules(dataSource.id)
    }
    
    // 3. 自动建模
    if (flowForm.value.autoSteps.includes('model')) {
      dataCleaningStore.saveToDataModel(dataSource)
    }
    
    // 4. 生成报表
    if (flowForm.value.autoSteps.includes('report')) {
      createAutoReport(dataSource)
    }
    
    ElMessage.success('数据流程创建成功')
    showFlowDialog.value = false
    
    // 根据自动步骤跳转到相应页面
    if (flowForm.value.autoSteps.includes('report')) {
      router.push('/designer')
    } else if (flowForm.value.autoSteps.includes('model')) {
      router.push('/data-model')
    } else {
      router.push('/data-cleaning')
    }
    
  } catch (error) {
    console.error('创建流程失败:', error)
    ElMessage.error('创建流程失败')
  }
}

const processFile = async (file) => {
  // 模拟文件处理
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        data: [
          { id: 1, name: '产品A', sales: 1000, category: '电子产品' },
          { id: 2, name: '产品B', sales: 1500, category: '家居用品' },
          { id: 3, name: '产品C', sales: 800, category: '电子产品' }
        ],
        columns: [
          { field: 'id', name: 'ID', dataType: 'number' },
          { field: 'name', name: '产品名称', dataType: 'text' },
          { field: 'sales', name: '销售额', dataType: 'currency' },
          { field: 'category', name: '类别', dataType: 'text' }
        ]
      })
    }, 1000)
  })
}

const getFileType = (filename) => {
  const ext = filename.split('.').pop().toLowerCase()
  return ext === 'csv' ? 'csv' : 'excel'
}

const createAutoReport = (dataSource) => {
  // 自动创建基础报表
  const numericFields = dataSource.columns.filter(col => 
    col.dataType === 'number' || col.dataType === 'currency'
  )
  const textFields = dataSource.columns.filter(col => col.dataType === 'text')
  
  if (numericFields.length > 0 && textFields.length > 0) {
    // 创建柱状图
    tableStore.addVisualization({
      type: 'bar',
      title: `${dataSource.name} - 柱状图`,
      data: {
        xAxis: textFields[0].field,
        yAxis: numericFields[0].field
      },
      position: { x: 100, y: 100 },
      size: { width: 400, height: 300 }
    })
  }
}

const importSampleData = () => {
  // 导入示例数据
  const sampleData = {
    name: '销售数据示例',
    type: 'sample',
    data: [
      { month: '1月', sales: 12000, profit: 3000, region: '北区' },
      { month: '2月', sales: 15000, profit: 4500, region: '北区' },
      { month: '3月', sales: 18000, profit: 5400, region: '南区' },
      { month: '4月', sales: 14000, profit: 4200, region: '南区' },
      { month: '5月', sales: 16000, profit: 4800, region: '东区' },
      { month: '6月', sales: 20000, profit: 6000, region: '东区' }
    ],
    columns: [
      { field: 'month', name: '月份', dataType: 'text' },
      { field: 'sales', name: '销售额', dataType: 'currency' },
      { field: 'profit', name: '利润', dataType: 'currency' },
      { field: 'region', name: '地区', dataType: 'text' }
    ],
    rowCount: 6
  }
  
  dataCleaningStore.addDataSource(sampleData)
  ElMessage.success('示例数据导入成功')
}

const createQuickReport = () => {
  if (modelCount.value === 0) {
    ElMessage.warning('请先创建数据模型')
    return
  }
  
  router.push('/designer')
}

const exportData = () => {
  ElMessage.info('导出功能开发中...')
}

// 根据数据状态自动设置当前步骤
const updateCurrentStep = () => {
  try {
    if (reportCount.value > 0) {
      currentStep.value = 5
    } else if (modelCount.value > 0) {
      currentStep.value = 4
    } else if (cleanedDataCount.value > 0) {
      currentStep.value = 3
    } else if (dataSourceCount.value > 0) {
      currentStep.value = 2
    } else {
      currentStep.value = 1
    }
  } catch (error) {
    console.warn('更新当前步骤时出错:', error)
    currentStep.value = 1
  }
}

// 初始化
onMounted(() => {
  updateCurrentStep()
})
</script>

<style scoped>
.data-flow-manager {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.flow-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.flow-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.flow-steps {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  flex: 1;
  padding: 16px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.step-item.active {
  background: #ecf5ff;
  border: 2px solid #409EFF;
}

.step-item.completed {
  background: #f0f9ff;
  border: 2px solid #67C23A;
}

.step-number {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #e4e7ed;
  color: #909399;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  transition: all 0.3s ease;
}

.step-item.active .step-number {
  background: #409EFF;
  color: white;
}

.step-item.completed .step-number {
  background: #67C23A;
  color: white;
}

.step-content {
  text-align: center;
}

.step-content h4 {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 14px;
}

.step-content p {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 12px;
}

.step-arrow {
  color: #c0c4cc;
  font-size: 20px;
}

.flow-status, .quick-actions {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
}

.status-header, .actions-header {
  margin-bottom: 12px;
}

.status-header h4, .actions-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.status-content {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.status-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  text-align: center;
}

.status-label {
  font-size: 12px;
  color: #606266;
}

.status-value {
  font-size: 18px;
  font-weight: 600;
  color: #409EFF;
}

.actions-content {
  display: flex;
  gap: 12px;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style>
